package com.xiongkw.lockutil;

import lombok.Data;
import redis.clients.jedis.Jedis;

@Data
public class LockableTaskExecutor {
    private LockableTaskExecutor(){}
    private Jedis redisClient;
    private DistributeLockPrefixEnum lockPrefixEnum;
    private String lockDataId;
    public static LockableTaskExecutor getInstance(Jedis jedis, DistributeLockPrefixEnum lockPrefixEnum, String lockDataId){
        LockableTaskExecutor excutor = new LockableTaskExecutor();
        excutor.setRedisClient(jedis);
        excutor.setLockPrefixEnum(lockPrefixEnum);
        excutor.setLockDataId(lockDataId);
        return excutor;
    }

    public void execute(LockableTask task){
        boolean lockSuccess = false;
        try {
            lockSuccess = DistributeLock.lock(redisClient,this.lockPrefixEnum,this.lockDataId);
            if(!lockSuccess){
                throw new RuntimeException("系统繁忙，请稍后再试！");
            }
            task.excute();
        } finally {
            if(lockSuccess){
                DistributeLock.unlock(redisClient,this.lockPrefixEnum,this.lockDataId);
            }
        }
    }
}
